# -*- coding: utf8 -*-

from project.sqlite3_db.table import Table

class TableImage2Image( Table ):

    _table_name = "image2image"

    def create( self ):
        cur = self.getCursor()

        # Create table
        cur.execute(
            "CREATE TABLE IF NOT EXISTS image2image ("+
            "id INTEGER PRIMARY KEY, "+
            "image1_id INTEGER, "+
            "image2_id INTEGER, "+
            "file1_id INTEGER, "+
            "file2_id INTEGER, "+
            "equal_proc INTEGER, "+
            "quality_points INTEGER)"
        )
        cur.execute(
            "CREATE INDEX IF NOT EXISTS images ON image2image (image1_id, image2_id, file1_id, file2_id)"
        )
        cur.close()
        return


    def insert_image2image( self, image1_id, image2_id, file1_id, file2_id, equal_proc, quality_points):

        cur = self.getCursor()

        cur.execute("INSERT INTO image2image("+
                    "image1_id, image2_id, file1_id, file2_id, equal_proc, quality_points"+
                    ") VALUES ("+
                    ":image1_id, :image2_id, :file1_id, :file2_id, :equal_proc, :quality_points"+
                    ")", {
            "image1_id":image1_id,
            "image2_id":image2_id,
            "file1_id":file1_id,
            "file2_id":file2_id,
            "equal_proc":equal_proc,
            "quality_points":quality_points
        })
        self.getConnection().commit()
        image_id = cur.lastrowid

        cur.close()
        return image_id

    def has_image2image(self, image1_id, image2_id):
        cur = self.getCursor()
        cur.execute("SELECT * FROM image2image WHERE"+
                    " (image1_id=:id1 AND image2_id=:id2) OR (image1_id=:id2 AND image2_id=:id1)",
                {"id1": image1_id, "id2":image2_id}
        )
        item = cur.fetchone()
        cur.close()
        if not item:
            item = False
        return item

    def remove_file_file2file(self, file_id):
        cur = self.getCursor()
        cur.execute(
            "DELETE FROM image2image WHERE file1_id=:id OR file2_id=:id",
                {"id": file_id}
        )
        self.getConnection().commit()
        rc = cur.rowcount
        cur.close()
        return rc

    pass
